const md5 = require('../util/md5')
const User = require('../models/index/User')

// 用户注册
exports.register = async function (userObj) {
  userObj.password = md5(userObj.password)
  const ins = await User.create(userObj)
  const data = ins.toJSON()
  delete data.password
  return data
}

// 登录
exports.login = async function (username, password) {
  password = md5(password)
  const result = await User.findOne({
    where: {
      username,
      password
    },
    attributes: { exclude: ['password', 'deleteAt'] }
  })
  if (result && result.username === username) {
    return result.toJSON()
  }
  // 用户不存在
  return null
}

// 获取所有用户
exports.getAllUser = async function () {
  return await User.findAll({
    attributes: { exclude: ['password'] }
  })
}

// 修改用户密码
exports.updateUser = async function (id, userObj) {
  if (userObj.password) {
    userObj.password = md5(userObj.password)
  }
  const result = await User.update(userObj, {
    where: {
      id
    }
  })
  return result
}

exports.getCurrentUser = async function (username) {
  const result = await User.findAll({
    where: {
      username
    },
    attributes: { exclude: ['password'] }
  })
  return result
}

// 这个可能不能用，需要测试
// 用主键查询用户,就是获取当前用户
exports.getUserById = async function (id) {
  // 通过主键来查询一条记录
  const result = await User.findByPk(id)
  if (result) {
    return result.toJSON()
  }
  return null
}

exports.deleteUser = async function (id) {
  return await User.destroy({ where: { id } })
}
